package com.example.redislearn.example.uv.service.impl;

import com.example.redislearn.example.uv.service.PvStatisticService;
import org.redisson.Redisson;
import org.redisson.api.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Service
public class PvStatisticServiceImpl implements PvStatisticService {

    @Resource
    private Redisson redisson;


    @Override
    public Boolean increasePv(String pageId, String userId) {
        // 使用管道加快速度
        RBatch batch = redisson.createBatch();
        RHyperLogLogAsync<String> hyperLogLog = batch.getHyperLogLog(pageId);
        RFuture<Boolean> future = hyperLogLog.addAsync(userId);
        batch.executeAsync();
        return future.isSuccess();

    }


    @Override
    public Boolean increaseBatch(String pageId, List<String> userId) {
        RBatch batch = redisson.createBatch();
        RHyperLogLogAsync<String> hyperLogLog = batch.getHyperLogLog(pageId);
        RFuture<Boolean> future = hyperLogLog.addAllAsync(userId);
        // 异步执行个人测试代码存在bug executeAsync 不推荐使用
        batch.execute();
        return future.isSuccess();
    }

    @Override
    public Long getPv(String pageId) throws ExecutionException, InterruptedException {
        RHyperLogLog<String> hyperLogLog = redisson.getHyperLogLog(pageId);
        return hyperLogLog.countAsync().get();
    }
}
